package com.capinfo.accumulation.service.collection.impl;


import com.capinfo.accumulation.model.collection.Company;
import com.capinfo.accumulation.model.collection.CompanyAccountFund;
import com.capinfo.accumulation.model.collection.CompanyAccountHistory;
import com.capinfo.accumulation.model.collection.CompanyHistory;
import com.capinfo.accumulation.parameter.collection.CompanyAccountFundHistoryParameter;
import com.capinfo.accumulation.parameter.collection.CompanyHistoryParameter;
import com.capinfo.accumulation.service.collection.CompanyAccountFundHistoryService;
import com.capinfo.accumulation.service.collection.CompanyHistoryService;
import com.capinfo.accumulation.service.collection.CompanyUtilService;
import com.capinfo.framework.dao.SearchCriteria;
import com.capinfo.framework.dao.SearchCriteriaBuilder;
import com.capinfo.framework.dao.impl.restriction.RestrictionExpression;
import com.capinfo.framework.exception.ObjectNotFoundException;
import com.capinfo.framework.service.impl.CommonsDataOperationServiceImpl;
import com.capinfo.framework.util.LogUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by cairunbin on 2017/10/24.
 */

public class CompanyAccountFundHistoryServiceImpl extends CommonsDataOperationServiceImpl<CompanyAccountHistory,CompanyAccountFundHistoryParameter> implements CompanyAccountFundHistoryService {

    private static final Log logger = LogFactory.getLog(CompanyHistory.class);

    @Autowired
    CompanyUtilService companyUtilService;



    @Override
    public CompanyAccountHistory saveOrUpdate(CompanyAccountFundHistoryParameter parameter) {

        CompanyAccountHistory companyAccountHistory = parameter.getEntity();
        CompanyHistory companyHistory  = parameter.getEntityCompany();

        Class<CompanyAccountHistory> entityClazz = parameter.getEntityClazz();
        Class<CompanyHistory> entityCompanyClazz = parameter.getEntityCompanyClazz();

         Company companyEntity = parameter.getCompanyEntity();
        Class<Company> companyEntityClazz = parameter.getCompanyEntityClazz();

        if (null == companyAccountHistory.getId()) {
            try {

                CompanyAccountHistory companyAccountHistory1 = getCompanyAccountFundByCompanyId(parameter.getCompanyId(),parameter);

                Company company1 = getGeneralService().getObjectById(companyEntityClazz,companyAccountHistory1.getCompanyHistoryId());

                System.out.println(company1.getGbCompanyName()+"、、单位名称");
                companyAccountHistory.setUnitName(company1.getGbCompanyName());

                //	基本公积金单位缴存比例+补充公积金单位缴存比例<=X%；基本公积金个人缴存比例+补充公积金个人缴存比例<=Y%（系统参数）
                if(companyAccountHistory1.getCompanyPaymentRatio()+companyAccountHistory.getCompanyPaymentRatio()<=12
                        &&companyAccountHistory1.getPersonPaymentRatio()+companyAccountHistory.getPersonPaymentRatio()<=12){

                    //	补充公积金缴存年月不能超过基本公积金缴存年月
                    System.out.println(companyAccountHistory.getStartPaymentDate()+"------"+companyAccountHistory1.getStartPaymentDate());
                    if (companyAccountHistory.getStartPaymentDate().getTime()<=companyAccountHistory1.getStartPaymentDate().getTime()){
                        //给补充账户设定公积金账户类型为:补充
                        Long accumulationFundAccountTypeId = 88L;
                        companyAccountHistory.setAccumulationFundAccountTypeId(accumulationFundAccountTypeId);



                        //生成单位补充公积金账号
                        Company company = getGeneralService().getObjectById(companyEntityClazz,parameter.getCompanyId());
                        String Code;
                        Code = companyUtilService.generateSupplyCompanyCode(company);
                        /*System.out.println("补充公积金账号"+Code);*/
                        companyAccountHistory.setCompanyAccount(Code);

                        //持久化
                        getGeneralService().persist(companyAccountHistory);
                    }else
                        return companyAccountHistory1;
                }else
                    return null;

                return companyAccountHistory;
            } catch (Exception e) {
                LogUtils.debugException(logger, e);
                throw e;
            }
        }else try {
            //获取单位公积金历史
            CompanyAccountHistory entityAccount = getGeneralService().getObjectById(entityClazz, parameter.getEntity().getId());
          /* CompanyHistory companyHistoryBack = getGeneralService().getObjectById(entityCompanyClazz, entityAccount.getCompanyHistoryId());*/

            //获取
            //根据单位公积金ID PersonHistoryAccountFundId查询
            //表单提交的不过滤，表单不提交的过滤掉
            BeanUtils.copyProperties(companyAccountHistory, entityAccount, new String[]{"id", "companyAccountFundId", "companyAccountFund", "companyHistoryId", "companyHistory", "companyAccount", "companyPaymentNumber", "gbdwzhzt", "companyAccountStateId", "companyAccountState", "companyCloseDate", "companyAccountBalance", "companyDepositNumber", "companyPaymentDate", "companyCloseReasonId", "companyCloseReason", "gbCompanyCloseReason", "paymentDate", "depositRateMark", "paymentPrecision", "accumulationFundAccountTypeId", "accumulationFundAccountType", "delegationPaymentId", "preTotalAmount", "totalInterest", "interest", "preMonthPayMonth", "lastPayMonth", "openDate", "startPayMonth", "dateTime", "bankCode", "operatorId", "operator", "regionId", "region", "siteId", "confirmerId", "confirmer", "confirmationTime", "channels", "createName", "companyAccountFundHistoryId"  });

           /* companyHistoryBack.addAccountHistory(entityAccount);*/
            getGeneralService().update(entityAccount);


            //保存成功之后将一些数据返回
            return entityAccount;


        } catch (Exception e) {

            LogUtils.debugException(logger, e);
            throw e;
        }
    }

    public CompanyAccountHistory getCompanyAccountHistoryById(Long id) {
        CompanyAccountHistory companyAccountHistory = null;
        //级联查询，根据Id得到单位信息历史和单位公积金历史
        try {
            companyAccountHistory = getGeneralService().getObjectById(CompanyAccountHistory.class, id);

        } catch (ObjectNotFoundException e) {
            LogUtils.debugException(logger, e);
        }
        return companyAccountHistory;
    }

    @Override
    public boolean auditInfo(Long id, Long companyAccountFundId, Long confirmerId) {
        CompanyAccountHistory companyAccountHistory = null;
        CompanyAccountFund companyAccountFund = null;

        Boolean token = false;
        companyAccountFund = getGeneralService().getObjectById(CompanyAccountFund.class,companyAccountFundId);
        if (companyAccountFund != null) {

            try {
                //单位公积金表与单位公积金历史表 一对多关联
                getGeneralService().fetchLazyProperty(companyAccountFund, "companyAccountHistory");
                companyAccountHistory = companyAccountFund.getCompanyAccountHistory().get(0);

                companyAccountHistory.setCompanyAccountFundId(companyAccountFundId);
                companyAccountFund.setCompanyAccountFundHistoryId(id);

                getGeneralService().update(companyAccountFund);
                token = true;
            }catch (Exception e) {

                LogUtils.debugException(logger, e);
            }
        }

        return token;
    }

    @Override
    public CompanyAccountHistory getCompanyAccountFundByCompanyId(Long companyId, CompanyAccountFundHistoryParameter parameter) {

        CompanyAccountHistory companyAccountHistory = parameter.getEntity();
        /*SearchCriteriaBuilder<CompanyAccountHistory> searchCriteriaBuilder = super.getSearchCriteriaBuilder(parameter);*/
        SearchCriteriaBuilder<CompanyAccountHistory> searchCriteriaBuilder = new SearchCriteriaBuilder<CompanyAccountHistory>(CompanyAccountHistory.class);
            searchCriteriaBuilder.addQueryCondition("companyHistoryId", RestrictionExpression.EQUALS_OP, parameter.getCompanyId());
            searchCriteriaBuilder.addQueryCondition("accumulationFundAccountTypeId", RestrictionExpression.EQUALS_OP, 87L);

            searchCriteriaBuilder.addOrderCondition("id", SearchCriteria.OrderRow.ORDER_DESC);
            //倒序取值
        CompanyAccountHistory companyAccountHistory1 = this.getGeneralService().getObjects(searchCriteriaBuilder.build()).get(0);

        return companyAccountHistory1;
    }

}





